﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Timers;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
using JKF.Substructure;

namespace JKF.Web
{
    public class Global : System.Web.HttpApplication
    {
        #region Sys
        void Application_Start(object sender, EventArgs e)
        {
            StartTimerTsk();
        }

        void Application_End(object sender, EventArgs e)
        {
            //  Code that runs on application shutdown
        }

        void Application_Error(object sender, EventArgs e)
        {
            // Code that runs when an unhandled error occurs
            StartTimerTsk();
        }

        void Session_Start(object sender, EventArgs e)
        {
            StartTimerTsk();
        }

        void Session_End(object sender, EventArgs e)
        {
        }
        #endregion

        #region Fields
        private static Timer _curTimer;
        private static int HarfDay = 43200000;
        #endregion

        #region Extentions
        /// <summary>
        /// 开启定时任务
        /// </summary>
        private void StartTimerTsk()
        {
            try
            {
                if (_curTimer == null)
                {
                    _curTimer = new Timer(Scheduler.Counter * 1000) { AutoReset = true };
                    _curTimer.Elapsed += Timer_Elapsed;
                }
                if (!_curTimer.Enabled) _curTimer.Enabled = true;
            }
            catch (Exception exp)
            {
                AppLogger.Log("SMS_StartTimerTsk", exp);
            }
        }

        /// <summary>
        /// 定时任务在此Run
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        static void Timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            try
            {
                _curTimer.Interval = HarfDay;//set interval to 12 hour to run task
                Scheduler.Run();
            }
            catch (Exception exp)
            {
                AppLogger.Log("Sms_Tmer_Elapsed", exp);
            }
            finally
            {
                //Reset Interval
                if (_curTimer.Interval != (Scheduler.Counter * 1000) && Scheduler.Counter != 0)
                {
                    _curTimer.Interval = Scheduler.Counter * 1000;
                }
            }
        }
        #endregion

    }
}
